#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
int main(int argc,char* argv[])
{
    if(argc!=3)
    {
        std::cerr<<"Usage: udp_client desc_ip desc_port"<<std::endl;
        return 1;
    }
    //创建网络文件
    int sock=socket(AF_INET,SOCK_DGRAM,0);
    if(sock < 0)
    {
         std::cerr<<"Usage: udp_client desc_ip desc_port"<<std::endl;
    }
    //填入目标套接字的信息
    struct sockaddr_in desc;
    memset(&desc,sizeof(desc),0);
    desc.sin_family=AF_INET;//通信的ip协议-ipv4
    desc.sin_port=htons(atoi(argv[2]));//字符转数字-传输格式转化
    desc.sin_addr.s_addr=inet_addr(argv[1]);//点分十进制字符转网络-自动会将主机格式转为网络格式
    //客户端不用主动绑定ip和port，当向远端发送消息是会自动绑定-服务端才需要固定的ip及port
    while(1)
    {
        std::cout<<"Please Enter# ";
        fflush(stdout);
        char buffer[128]={0};
        ssize_t size=read(0,buffer,sizeof(buffer)-1);
        if(size>0)
        {
            buffer[size-1]=0;//覆盖回车符
            sendto(sock,buffer,strlen(buffer),0,(struct sockaddr*)&desc,sizeof(desc));
            struct sockaddr_in peer;
            socklen_t len=sizeof(peer);
            ssize_t s=recvfrom(sock,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&peer,&len);
            if(s>0)
            {
                buffer[s]=0;
                std::cout<<"Echo# "<<buffer<<std::endl;
            }
        }
    }
    close(sock);
    return 0;
}
